package cm309.BookingSystem.FM.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cm309.BookingSystem.common.Common;
import cm309.BookingSystem.common.MyConnection;
import cm309.BookingSystem.mb.model.Member;
import cm309.BookingSystem.tm.model.Trainer;


public class CreateFMAction implements Action {

	private static final String MemberName = null;
	private static final String MemberID = null;
	private static final String PASSWORD = null;
	private static final String EMAIL = null;

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		MyConnection con=new MyConnection();

		
		try {
			Long oldtrainerIDnum=Long.parseLong(con.getOneField(
					"Select MEMBERID from BK_FM_member order by MemberID DESC"));
			
			//update
			PreparedStatement ps=con.getPS(
					"INSERT INTO BK_FM_MEMBER ( Name," +MemberID + MemberName+ "PASSWORD+ BONUSPOINT +MEMBERAGE +EMAIL) VALUES (?,?,?,?,?,?)");
			
			//set the Trainer
			Member M=new Member();
			String formatStr="%08d";
			
			M.setMemberID(String.format(formatStr, oldtrainerIDnum+1));		
			M.setMemberName(request.getParameter("MemberName"));
			M.setPASSWORD(request.getParameter("asw@123").charAt(0));
			M.setTrainerAge(Integer.parseInt(request.getParameter("trainerAge")));
			M.setClassification(request.getParameter("classification"));
			

			ps.setString(1, M.getMemberName());
		    ps.setString(2,Character.toString(M.getPASSWORD()));
			ps.setInt(3,M.getMemberAge());
			ps.setString(4,M.getClassification());
			ps.setString(5,M.getMemberID());
			int count=ps.executeUpdate();
			if (count!=1) {
				throw new RuntimeException("Insert Member Error");
			}
			
			con.commit();
	
			 //redirect to the show product!
			PrintWriter w = response.getWriter();
		
			w.println(Common.beanToJson(M));
			  			
		} catch (SQLException e) {

			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			
			con.close();
		}

	}

	private void BONUSPOINT(String email2) {
		// TODO Auto-generated method stub
		
	}

	private void MEMBERAGE(String string) {
		// TODO Auto-generated method stub
		
	}

	public static String getEmail() {
		return EMAIL;
	}

	public static String getPassword() {
		return PASSWORD;
	}

}
